package com.wHitE.servlet;

import com.google.gson.Gson;
import com.wHitE.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        String filename = req.getParameter("filename");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        // 获取资源下载路径
        String path = req.getServletContext().getRealPath("/download/");
        // 通过路径创建file对象
        File file = new File(path);
        // 判断文件是否存在且是否为标准文件
        if (file.exists() && file.isFile()) {
            // 设置响应类型 设置成浏览器无法使用或者激活某个程序来处理的 MIME类型-> 如 application/octet-stream或者 application/x-msdownload
            // 设置响应头
            resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
            // 获取输入流
            InputStream inputStream = new FileInputStream(file);
            // 获取servlet字节输出流
            ServletOutputStream outputStream = resp.getOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            // 循环输出
            while ((len = inputStream.read(bytes)) != -1) {
                // 输出内容
                outputStream.write(bytes, 0, len);
            }

        } else {
            out.print(gson.toJson(Result.error("文件不存在!")));
        }
    }
}
